package com.xiaohudie.util;

import javafx.fxml.Initializable;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.AbstractDataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.HashMap;
import java.util.ResourceBundle;
import java.util.logging.Logger;

/**
 * @Author xiao hu die
 * @Date 2022/4/6 10:30
 * @Version 1.0
 */
@Component
@Primary
public class DynamicDataSource extends AbstractRoutingDataSource {
    //当前的数据源标识
    public static ThreadLocal<String> name  =new ThreadLocal<>();
    /**5.1*/
    @Resource
    DataSource dataSource1;
    /**8.0*/
    @Resource
    DataSource dataSource2;
    /**告诉AbstractRoutingDataSource使用哪个数据源*/
    @Override
    protected Object determineCurrentLookupKey() {
        return name.get();
    }
    @Override
    public void afterPropertiesSet()  {
    /**为targetDataSources初始化所有数据*/
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("R",dataSource1);
        objectObjectHashMap.put("W",dataSource2);
        super.setTargetDataSources(objectObjectHashMap);
        super.setDefaultTargetDataSource(dataSource2);
        super.afterPropertiesSet();

    }

}
